package com.cls.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cls.business.entity.Notice;
import com.cls.business.entity.TopicPlan;
import com.cls.business.entity.TopicSelect;
import com.cls.business.entity.Topic;
import com.cls.business.mapper.NoticeMapper;
import com.cls.business.mapper.TopicPlanMapper;
import com.cls.business.mapper.TopicSelectMapper;
import com.cls.business.mapper.TopicMapper;
import com.cls.business.service.ITopicSelectService;
import com.cls.business.vo.TopicSelectVO;
import com.cls.common.entity.QueryRequest;
import com.cls.common.enums.TemplatesFileName;
import com.cls.common.exception.MyException;
import com.cls.common.utils.ReportUtil;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import com.cls.common.enums.DictEnum;
import com.cls.common.utils.FileUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wuwenze.poi.annotation.Excel;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;

/**
 * 征集选题 Service实现
 *
 * @author wmm
 * @date 2020-11-12 09:22:38
 */
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class TopicSelectServiceImpl extends ServiceImpl<TopicSelectMapper, TopicSelect> implements ITopicSelectService {

    private final TopicMapper topicMapper;
    private final TopicPlanMapper topicPlanMapper;
    private final NoticeMapper noticeMapper;


    @Override
    public PageInfo<TopicSelect> findTopicSelects(QueryRequest request, TopicSelect topicSelect) {
        LambdaQueryWrapper<TopicSelect> queryWrapper = new LambdaQueryWrapper<>();
        if (topicSelect.getYear() == null) {
            Calendar calendar = Calendar.getInstance();
            topicSelect.setYear(calendar.get(Calendar.YEAR) + "");
        }
        queryWrapper.eq(TopicSelect::getYear, topicSelect.getYear());
        //必须查询已提交的数据
        queryWrapper.eq(TopicSelect::getIsSubmit, Boolean.TRUE);
        if (StringUtils.isNotEmpty(topicSelect.getTopicName())) {
            queryWrapper.like(TopicSelect::getTopicName, topicSelect.getTopicName());
        }
        if (topicSelect.getCreateBy() != null) {
            queryWrapper.like(TopicSelect::getCreateBy, topicSelect.getCreateBy());
        }

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<TopicSelect> list = this.list(queryWrapper);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public PageInfo<TopicSelectVO> findTopicSelectsForClient(QueryRequest request, TopicSelectVO topicSelect) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<TopicSelectVO> list = this.baseMapper.selectTopicSelectsForClient(topicSelect);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public TopicSelectVO findTopicDetailForClient(Long topicSelectId) {
        return this.baseMapper.selectDetailForClient(topicSelectId);
    }


    @Override
    public void changeTopics(String[] ids, Topic topic) {
        List<String> list = Arrays.asList(ids);
        list.forEach(id -> {
            TopicSelect topicSelect = this.baseMapper.selectById(id);
            topic.setYear(topicSelect.getYear());
            topic.setTopicName(topicSelect.getTopicName());
            topic.setSelectId(topicSelect.getSelectId());
            topic.setSubjectTypeCodes(topicSelect.getSubjectTypeCodes());
            topic.setDeclareNum(0);
            topic.setQualifiedPassNum(0);
            topic.setProjectNum(0);
            TopicPlan topicPlan = topicPlanMapper.selectBySelectNoticeId(topicSelect.getNoticeId());
            if (topicPlan.getIsGenerateCode()) {
                throw new MyException("对不起，" + topicSelect.getTopicName() + "课题已生成课题编号不可进行转换！");
            }
            //如果是委托课题则不添加planId
            if (DictEnum.ENTRUST.getCode().equals(topic.getTopicClassifyCode())) {
                topic.setPlanId(null);
            } else {
                topic.setPlanId(topicPlan.getPlanId());
            }
            topic.setStatusTypeCode(DictEnum.PLAN_CREATE.getCode());
            topic.setYear(topicPlan.getYear());
            topicMapper.insert(topic);
            topicSelect.setIsChange(Boolean.TRUE);
            this.baseMapper.updateById(topicSelect);
        });
    }

    @Override
    public List<TopicSelect> findTopicSelects(TopicSelect topicSelect) {
        LambdaQueryWrapper<TopicSelect> queryWrapper = new LambdaQueryWrapper<>();
        // TODO 设置查询条件
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 判断当前通知公告是否过期
     *
     * @param noticeId
     */
    private void checkTopicSelectValid(Long noticeId) {
        TopicPlan topicPlan = topicPlanMapper.selectBySelectNoticeId(noticeId);
        Date date = new Date();
        int compareNoBegin = DateUtil.compare(topicPlan.getSelectBeginTime(), date);
        int compareOver = DateUtil.compare(topicPlan.getSelectEndTime(), date);
        if (compareNoBegin > 0) {
            throw new MyException("对不起，当前课题征集还未开始！");
        }
        if (compareOver < 0) {
            throw new MyException("对不起，当前课题征集已过期！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createTopicSelect(TopicSelect topicSelect) {
        //判断此课题征集是否过期
        checkTopicSelectValid(topicSelect.getNoticeId());

        //获取计划中的年份并设置到课题征集中
        Long noticeId = topicSelect.getNoticeId();
        TopicPlan topicPlan = topicPlanMapper.selectBySelectNoticeId(noticeId);
        topicSelect.setYear(topicPlan.getYear());
        this.save(topicSelect);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTopicSelect(TopicSelect topicSelect) {
        this.saveOrUpdate(topicSelect);
    }


    /**
     * 删除
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTopicSelects(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.removeByIds(list);
    }

    @Override
    public void export(String year, HttpServletResponse response) throws Exception {

        List<TopicSelectVO> topicSelectList = this.baseMapper.selectList4Export(year);

        File file = ReportUtil.getFile(TemplatesFileName.TOPIC_SELECT_CON.getTemplateName());
        ExcelReader reader = ExcelUtil.getReader(file);
        ExcelWriter writer = reader.getWriter();
        int nowRowIndex = 2;
        writer.setCurrentRow(nowRowIndex);
        List<List<String>> rows = new ArrayList<>();
        for (int i = 0; i < topicSelectList.size(); i++) {
            TopicSelectVO item = topicSelectList.get(i);
            List<String> row = CollUtil.newArrayList("" + (i + 1), item.getSubjectTypeNames(), item.getTopicName(), item.getProveContent(), item.getExcelConcatWs());
            rows.add(row);
        }
        writer.write(rows);
        String fileName = String.format(TemplatesFileName.TOPIC_SELECT_CON.getFileName(), year);
        //可以自适应宽度
//        writer.autoSizeColumnAll();
        FileUtil.downloadExcel(writer, file, fileName, response);
    }

    @Override
    public void submitTopicSelect(TopicSelect topicSelect) {
        //判断此课题征集是否过期
        checkTopicSelectValid(topicSelect.getNoticeId());
        topicSelect.setIsSubmit(true);
        this.baseMapper.updateById(topicSelect);
    }


   /* @Override
    public void export(String year, HttpServletResponse response) throws Exception {
        LambdaQueryWrapper<TopicSelect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TopicSelect::getYear, year);
        queryWrapper.eq(TopicSelect::getIsSubmit, Boolean.TRUE);
        List<TopicSelect> topicSelectList = this.list(queryWrapper);

        ExcelWriter writer = ExcelUtil.getWriter();

//        writer.getCellStyle().setFont(font);
//        writer.setRowHeight(1, 300);
        //设置内容字体
        Font font = writer.createFont();
        font.setBold(true);
//        font.setFontHeightInPoints((short) 18);
        font.setFontHeight((short) 100);
        //第二个参数表示是否忽略头部样式
        writer.getStyleSet().setFont(font, true);
        writer.setRowHeight(0,100);
        writer.merge(5, "中国法学会2017年度部级法学研究课题建议征集汇总表", false);

       *//* font.setBold(false);
        font.setFontHeightInPoints((short) 12);
        //第二个参数表示是否忽略头部样式
        writer.getStyleSet().setFont(font, true);*//*

        writer.setRowHeight(0,100);
        Map<String, Object> row1 = new LinkedHashMap<>();
        row1.put("姓名", "张三");
        row1.put("年龄", 23);
        row1.put("成绩", 88.32);
        row1.put("是否合格", true);
        row1.put("考试日期", DateUtil.date());

        Map<String, Object> row2 = new LinkedHashMap<>();
        row2.put("姓名", "李四");
        row2.put("年龄", 33);
        row2.put("成绩", 59.50);
        row2.put("是否合格", false);
        row2.put("考试日期", DateUtil.date());

        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(row1, row2);
        writer.write(rows, true);
        //自适应列宽度
        writer.autoSizeColumnAll();
        String fileName = "中国法学会" + year + "年度部级法学研究课题建议征集汇总表.xlsx";
        FileUtil.downloadExcel(writer, fileName, response);
    }*/

}
